package com.liuguang.article.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.liuguang.api.article.ArticleService;
import com.liuguang.article.dao.ArticleContentMapper;
import com.liuguang.article.dao.ArticleMapper;
import com.liuguang.api.article.pojo.ArticleContentDo;
import com.liuguang.api.article.pojo.ArticleDo;
import com.liuguang.api.redis.RedisService;
import com.liuguang.common.constans.CommonConstans;
import com.liuguang.api.article.dto.ArticleDTO;
import com.liuguang.common.enums.CommonResultEnum;
import com.liuguang.common.enums.RedisPreFixEnum;
import com.liuguang.common.pojo.CommonResult;
import com.liuguang.api.gateway.security.pojo.bo.AuthUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: ArticleServiceImpl
 * @Description：
 * @Author: wanghr
 * Date: 3:18 PM 2020/10/17
 * Version: 1.0
 */
@DubboService
@Service
public class ArticleServiceImpl implements ArticleService {
    private static final Logger logger = LoggerFactory.getLogger(ArticleServiceImpl.class);

//    @Autowired
//    private ArticleMapper articleMapper;
    @Autowired
    private ArticleContentMapper articleContentMapper;

    @DubboReference(timeout = 40000)
    private RedisService redisService;

    @Autowired
    private PageHelper pageHelper;

    /**
     * 创建文章对象：文章标题、分类、主体内容、点赞数、评论数、
     * 需要创建的表：  文章表： id、分类id、文章标题、文章作者、文章是否是草稿、点赞数、
     * 文章内容表：
     * 分类表：id、文章类别名称、类别所属创建者、
     * 评论表：id、文章id、是回复评论的id、评论人的id、评论内容、评论的点赞数、
     * 行为记录表：id、被记录行为的人id、对文章行为：点赞创建修改删除评论、文章id、
     * <p>
     * 在什么地方获取文章？当文章中包含图片的时候文件的大小是否影响上传?
     * 使用富文本编辑器能将图片编程一个url地址吗？图片保存到云存储上
     * <p>
     * 文章保存到哪里？
     * <p>
     * 发布后需要处理哪些事情？
     * 更新 ES 中数据
     *
     * @params: [request, response]
     * @return: com.liuguang.common.pojo.CommonResult<?>
     */
    @Override
    public CommonResult<?> publish(ArticleDTO articleDTO) {
        logger.info("进入ArticleServiceImpl");

        //在redis获取用户信息
        String userInfoKey = RedisPreFixEnum.SAVE_USER_INFO.getValue() + articleDTO.getAuthorName();
        CommonResult<String> redisResult = redisService.get(userInfoKey);
        if (!CommonResultEnum.SUCCESS.getCode().equals(redisResult.getCode())) {
            return CommonResult.fail(CommonConstans.REDIS_GET_USER_INFO_FAIL);
        }
        String data = redisResult.getData();
        logger.info("data:{}", data);
        AuthUser currentUser = JSONObject.parseObject(data, AuthUser.class);
        logger.info("redis的String数据解析成user类：{}", currentUser);
        String articleContent = articleDTO.getArticleContent();

        logger.info("文章长度：{}", articleDTO.getArticleContent().length());
        String articlePicture = null;
        String articleEpitome = null;
        if (StringUtils.isNotEmpty(articleContent)) {
            int tagStart = articleContent.indexOf("<");
            int tagEnd = articleContent.indexOf(">");
            //文章中包含图片
            if (tagStart >= 0) {
                //保存文章首个图片，供列表展示
                articlePicture = articleContent.substring(tagStart, tagEnd + 1);

                //保存文章前30个字符，供列表展示
                StringBuilder stringBuilder = new StringBuilder();
                articleEpitome = getAraticleEpitome(articleContent, tagStart, tagEnd, stringBuilder);
            }
        }
        logger.info("文章的概要信息：{},长度：{}", articleEpitome, articleEpitome.length());
        //构建存储对象
        ArticleDo articleDo = new ArticleDo();
        articleDo.setUserId(currentUser.getId());
        articleDo.setArticleName(articleDTO.getArticleName());
        articleDo.setArticlePicture(articlePicture);
        articleDo.setArticleEpitome(articleEpitome);
        articleDo.setArticleType(CommonConstans.DELATE_DEFULT);
        articleDo.setArticleAuthor(currentUser.getUsername());
        articleDo.setCommentCount(CommonConstans.DELATE_COUNT);
        articleDo.setLikeCount(CommonConstans.DELATE_COUNT);
        articleDo.setIsDeleted(CommonConstans.DELATE_DEFULT);
        articleDo.setCreateTime(new Date());
        articleDo.setUpdateTime(new Date());
//        articleMapper.insert(articleDo);

        if (StringUtils.isNotEmpty(articleContent)) {
            ArticleContentDo articleContentDo = new ArticleContentDo();
            articleContentDo.setArticleContent(articleContent);
            articleContentMapper.insert(articleContentDo);
        }

        //使用rabbitmq更新Es库

        return CommonResult.success("新增文章成功");
    }

    @Override
    public CommonResult<List<ArticleContentDo>> getAllArticleData(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ArticleContentDo> articleDoList = articleContentMapper.getAllArticleData();
        String articleAuthor = articleDoList.get(0).getArticleAuthor();
        System.out.println("articleAuthor = " + articleAuthor);
        logger.info("获取articleDoList的数量：{}",articleDoList);
        return CommonResult.success(CommonResultEnum.SUCCESS.getMsg(),articleDoList);
    }


    private String getAraticleEpitome(String articleContent, int tagStart, int tagEnd, StringBuilder stringBuilder) {
        int length = stringBuilder.length();
//        logger.info("现在长度：{}", length);
        if (length < 30) {
            stringBuilder.append(articleContent.substring(0, tagStart));
            articleContent = articleContent.substring(tagEnd + 1);
//            logger.info("截取后articleContent：{}", articleContent);
            tagStart = articleContent.indexOf("<");
            tagEnd = articleContent.indexOf(">");
//            logger.info("tagStart:{},tagEnd:{}", tagStart, tagEnd);
            if (tagStart != -1) {
                return getAraticleEpitome(articleContent, tagStart, tagEnd, stringBuilder);
            } else {
                if (articleContent.length() > 30 - length) {
                    stringBuilder.append(articleContent.substring(0, 30 - length));
                } else {
                    stringBuilder.append(articleContent);
                }
                return stringBuilder.toString();
            }
        } else if (length > 30) {
            return stringBuilder.substring(1, 30);
        } else {
            return stringBuilder.toString();
        }
    }
}




















